Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

60
Vistas
C# | Create a json string out of static class fields with values

I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s. Key value pairs saved in string, could be wrapped at the end like

    ResultString = "{ " + resultString + " }";

C# .NET 4.7.2 (console app)

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

As others have said, a static class is not a good design here.

However, it is possible to map it back to JSON with some simple reflection:

public static JObject MapStaticClassToJson(Type staticClassToMap)
{
    var result = new JObject();
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    {
        result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
    }
    
    return result;
}
over 4 years ago · Santiago Trujillo Denunciar

0

I think it would be nice to have some simple code to assign json properties to a static class properties too. I created this code using @RichardDeeming answer

public static void MapStaticClassFromJson(string json, Type staticClassToMap)
{
    var jsonObject = JObject.Parse(json);
        
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    prop.SetValue(null, Convert.ChangeType(jsonObject[prop.Name], prop.PropertyType, CultureInfo.CurrentCulture), null);
}

test

 MapStaticClassFromJson(json,typeof(Data));
 Console.WriteLine(Data.StaticPropertyName_int); 
 Console.WriteLine(Data.StaticPropertyName_string);

result

34
string_value_of_this_property
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda